<script setup>
  import SideBar from '@/components/SideBar.vue'
  import Bar from '@/components/Bar.vue'
  import SendForm from '@/components/SendForm.vue'
  import MessageItem from '@/components/MessageItem.vue'
  import Welcome from '@/components/Welcome.vue'
  import Modal from '@/components/Modal.vue'
  import useMessage from '@/lib/hooks/useMessage.js'
  import useChats from '@/stores/chats'
  import useAside from '@/stores/aside'
  import useLoadingStore from '@/stores/loading'


  const { chats, index, add: addMessage, messages } = useChats()

  const aside = useAside()

  const { messageList, send } = useMessage(scrollToBottom)
  const loading = useLoadingStore()
  function onSend(content) {
    send(content)
  }

  const chatListRef = ref()
  // 滚动到底部
  function scrollToBottom() {
    const el = chatListRef.value
    if (!el) {
      return
    } else {
      const scrollHeight = el.scrollHeight;
      const clientHeight = el.clientHeight;
      const scrollTop = scrollHeight - clientHeight;
      el.scrollTo({
        top: scrollTop,
        behavior: "smooth"
      })
    }
  }

  // nextTick(() => {
  //   scrollToBottom()
  // })

  watch(messageList, () => {
    nextTick(() => {
      scrollToBottom()
    })
  })
</script>

<template>

  <Modal :open="aside.status" @close="aside.close">
    <div class="h-full min-h-0">
      <SideBar />
    </div>

  </Modal>

  <div class="flex w-full h-full overflow-hidden">
    <!-- sidebar -->
    <div class="bg-slate-900 hidden md:w-[260px] md:flex md:flex-col md:shrink-0">
      <div class="flex-1 min-h-0">
        <SideBar />
      </div>
    </div>

    <!-- main -->
    <div class="relative flex flex-col flex-1 h-full">
      <div class="sticky top-0 flex items-center w-full bg-slate-800 md:hidden">
        <Bar @openSidebar="aside.open" />

        <div class="flex items-center justify-center flex-1">
          <img src="/logo2_inverse_sm.png" class="w-auto h-5 border-green-500" />
        </div>
      </div>
      <main class="flex flex-col flex-1 pb-32 overflow-y-auto" ref="chatListRef">
        <div class="flex-1 p-4">
          <template v-if="messageList.length">
            <div class="bg-black/5" v-for="d, i in messageList" :key="i">
              <MessageItem :item="d" :index="i" :talking="messageList.length - 1 == i ? loading.talking : false" />
            </div>
          </template>
          <Welcome v-else />
        </div>

        <div class="absolute bottom-0 left-0 w-full bg-white border-t border-black/10">
          <SendForm @send="onSend" />
        </div>

      </main>
    </div>
  </div>
</template>